<?php

namespace frontendm\models;

use common\models\User;
use yii\base\Model;
use Yii;
use common\components\MTools;
use frontendm\models\WB_UserProfile;
use frontendm\models\WB_UserAccountHy;

/**
 * Signup form
 */
class SignupForm extends Model {

    public $username;
    public $phone;
    public $password;
    public $repassword;
    public $invite_code;
    public $truename;
    public $alipay;
    public $qq;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            ['username', 'filter', 'filter' => 'trim'],
            ['username', 'required', "message" => "用户名不能为空"],
            ['username', 'checkmatchEg'],
            ['username', 'unique', 'targetClass' => '\common\models\User', 'message' => '用户名已存在'],
            ['username', 'string', 'min' => 2, 'max' => 255],
            ['password', 'required', "message" => "密码不能为空"],
            ['password', 'string', 'min' => 6],
//            [["alipay"], "required", "message" => "请输入支付宝账号"],
//            [["alipay"], "checkalipay"],
            ["invite_code", "required", "message" => "请填写邀请码"],
            ["invite_code", "checkinvitecode"],
            //[["alipay"], "unique", 'targetClass' => '\common\models\UserProfile', "message" => "该支付宝账号已经被注册，请更换"],
            [["repassword"], "compare", "compareAttribute" => "password", "message" => "两次密码不一致"],
        ];
    }

    public function checkalipay($attribute, $params) {
        if (!$this->hasErrors()) {
            $emailpattern = '/^[a-zA-Z0-9!#$%&\'*+\\/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&\'*+\\/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/';
            $phonepattern = '/^((0\\d{2,3}(-){0,1}\\d{7,8})|(1[3584]\\d{9}))$/';
            if (!(preg_match($emailpattern, $this->alipay) || preg_match($phonepattern, $this->alipay))) {
                $this->addError($attribute, '支付宝账号只能输入邮箱和手机号码！');
            }
        }
    }

    public function checkinvitecode($attribute, $params) {
        if (!$this->hasErrors()) {
            $user = User::find()->where("my_code=:invite_code", [":invite_code" => $this->invite_code])->one();
            if (!$user instanceof User || $user->role != 2) {
                $this->addError($attribute, '您填写的邀请码无效！');
            }
        }
    }

    public function checkmatchEg($attribute, $params) {
        if (!$this->hasErrors()) {
            $plen = strlen($this->username);
            if (!preg_match("/^(([a-z]+[0-9]+)|([0-9]+[a-z]+))[a-z0-9]*$/i", $this->username) || $plen < 6 || $plen > 15) {
                $this->addError($attribute, '用户名必须为6-15位的数字和字母的组合');
            }
        }
    }

}
